<template>
  <div id="header-user">
    <a class="user-btn" v-if="!userInfo" @click="openLogin">
      <img src="@/assets/user.png">
    </a>
    <template v-else>
      <img class="user-avatar" :src="userInfo.avatar"/>
      <span class="user-name">{{ userInfo.nickname }}</span>
      <ul class="user-submenu">
        <li>
          <router-link to="/user/userInfo">
            <i class="iconfont icongerenzhongxin"/> 个人中心
          </router-link>
        </li>
        <li>
          <a @click="logout"><i class="iconfont icontuichu"/> 退出</a>
        </li>
      </ul>
    </template>
  </div>
</template>

<script>
import {logout} from "@/api/user";
import {removeToken, removeLocalUserInfo} from "@/utils/auth";

export default {
  name: "header-user",
  data() {
    return {
      userInfo: this.$store.state.userInfo
    }
  },
  watch: {
    "$store.state.userInfo": {
      handler: function () {
        this.userInfo = this.$store.state.userInfo
      }
    }
  },
  created() {
  },
  methods: {
    openLogin() {
      this.$store.dispatch('setLoginDialog', true);
    },
    logout() {
      logout().then(res => {
        console.log(res.message);
        removeToken();
        removeLocalUserInfo();
        this.userInfo = null;
        const currentRoute = this.$router.currentRoute.fullPath;
        if (currentRoute !== '/') {
          this.$router.push({path: '/'});
        }
        this.$message.success("注销成功");
      }).catch(err => {
        console.log(err)
      });
    }
  }
}
</script>

<style scoped lang="less">
.user-btn img, .user-avatar {
  width: 40px;
  height: 40px;
}

.user-name {
  padding-left: 5px;
  position: relative;
  top: -15px;
}

.user-avatar {
  cursor: pointer;
  border-radius: 50%;
}

#header-user:hover .user-submenu {
  display: block;
}

.user-submenu {
  position: absolute;
  display: none;
  right: 0;
  width: 120px;
  height: 65px;
  margin-right: 30px;
  margin-top: 8px;
  box-shadow: 0 5px 20px -4px rgba(0, 0, 0, 0.5);
  background-color: #fff;
  animation: submenu 0.3s 0.1s ease both;
}

.user-submenu:before {
  position: absolute;
  top: -8px;
  left: 0;
  width: 100%;
  height: 20px;
  content: "";
}

.user-submenu a {
  line-height: 2;
  color: #4c4948 !important;
  text-shadow: none;
  display: block;
  padding-left: 14px;
  text-decoration: none;
}

.user-submenu a:hover {
  background: #4ab1f4;
}

ul {
  list-style: none;
}

</style>
